<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Grid;
use App\Models\GridImg;
use App\Models\ProtocolSet;
use App\Models\BuildForm;
use App\Models\ApprovalSet;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Validator;

//type1:户口本2土地证3房产证4其他证明5签约6腾房7建房手续8无任何材料
class GridImgController extends Controller
{
    // 录入
    public function addImg(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'grid_id' => 'required',
            'imgs_data' => 'required',
        ], [
            'grid_id.required' => '请输入网格id',
            'imgs_data.required' => '请输入数据',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $data['do_user_id']=auth('api')->user()->id??0;
        $data['grid_id']=$params['grid_id'];
        try {
            $imgs_data=json_decode($params['imgs_data'],true);
            foreach($imgs_data as $vv){
            //    if(!$vv['imgs']){
            //     return showError('照片不能为空');
            //    }
               if(!$vv['type']){
                return showError('类型不能为空');
               }
               $gridData=Grid::query()->select('mapping_company_id','if_sign')->where('id',$params['grid_id'])->first();
               if(in_array($vv['type'],[4,7,8])&&$gridData['mapping_company_id']==''){
                 return showError('选择建房手续/其他证明/无任何材料，必须进行测绘');
               }

               if($vv['type']==6&&$gridData['if_sign']==0){
                return showError('请先完成签约操作');
               }
            }

            foreach($imgs_data as $v){
                $data['imgs']=$v['imgs'];
                $data['type']=$v['type'];
                $data['num']=$v['num']??'';
                $data['villager_id']=$v['villager_id']??0;
                $res=GridImg::query()
                ->updateOrCreate(['grid_id'=>$params['grid_id'],'type'=>$v['type'],'villager_id'=>$data['villager_id']],$data);
               
                if($v['type']==1){
                    // $this->setRuhuStatus($params['grid_id'],'hukou_status');
                    Grid::query()->where('id',$params['grid_id'])->update(['hukou_status'=>2]);
                     // 触发审批-完成户口
                     if(!$this->findApproval($params['grid_id'], 24)){
                        $this->setApproval($params['grid_id'],24);
                    }
                }elseif($v['type']==2||$v['type']==3||$v['type']==4||$v['type']==7||$v['type']==8){
                    // $this->setRuhuStatus($params['grid_id'],'fangchan_status');
                    Grid::query()->where('id',$params['grid_id'])->update(['fangchan_status'=>2]);
                     // 触发审批-完成土地证
                     if(!$this->findApproval($params['grid_id'], 25)){
                        $this->setApproval($params['grid_id'],25);
                    }
                }elseif($v['type']==5||$v['type']==6){//签约/腾房
                    $template_arr=[5=>19,6=>20];
                    $grid=Grid::query()->select('project_id','street_id','village_id')->where('id',$params['grid_id'])->first();
                    $approval_set=ApprovalSet::query()
                    ->where('project_id',$grid['project_id']??2)
                    ->where('street_id',$grid['street_id']??3)
                    ->where('village_id',$grid['village_id']??1)
                    ->where('template_id',$template_arr[$v['type']])
                    ->where('status',1)
                    ->value('id');
                    $status=[5=>'sign_status',6=>'vacate_room_status'];
                    if($approval_set){//有审批
                        Grid::query()->where('id',$params['grid_id'])->update([$status[$v['type']]=>2]);

                        // 触发审批-完成 签约/腾房
                        if(!$this->findApproval($params['grid_id'], $template_arr[$v['type']])){
                            $this->setApproval($params['grid_id'],$template_arr[$v['type']]);
                        }
                    }else{
                        Grid::query()->where('id',$params['grid_id'])->update([$status[$v['type']]=>1]);
                    }    
                }
            }

            return showSuccess('提交成功！');
        } catch (\Exception $e) {
            return showError($e->getMessage());
        }
       
    }

    // 回显
    public function imgList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'grid_id' => 'required',
            'type' => 'required',
        ], [
            'grid_id.required' => '请输入网格id',
            'type.required' => '请输入类型',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $type=explode(',',$params['type']);

        $data=Grid::query()
        ->select('id','name','house_use','supply_form','build_form','street_id','village_id','project_id','segment_id','if_sign','for_user_id','if_mapping','if_build','sign_time','sign_num')
        ->where('id',$params['grid_id'])
        ->with('villager:id,name,identity_card,phone,grid_id')
        ->with('agent:name,identity_card,phone,grid_id')
        ->with('village:name,id')
        ->with(['grid_img'=> function ($query) use ($type) {
            $query->select('imgs','grid_id','villager_id','num','type')->whereIn('type', $type);
        }])
        ->first();

        if($data){
            foreach($data['grid_img'] as &$v){
                $v['imgs']=$v['imgs']?$this->getImageUrl($v['imgs'],1):[];
                $li[$v['type']][]=$v;
            }
            $data['grid_img_arr']=$li??[];
            $data['villager_name']=implode(',',array_column(json_decode($data['villager']),'name'));
        }

        if(in_array(6,$type)){
            $data['build_form_name']=BuildForm::query()->where('id',$data['build_form'])->value('name');

            $protocol_set=ProtocolSet::query()
            ->select('id','require_clear_time')
            ->where('supply_form',$data['supply_form'])
            ->where('build_form',$data['build_form'])
            ->where('street_id',$data['street_id'])
            ->where('village_id',$data['village_id'])
            ->where('project_id',$data['project_id'])
            ->where('segment_id',$data['segment_id'])
            ->first();
    
            if(empty($protocol_set)){
                return showError('未查询到配置信息，请联系管理员到后台配置');
            }

            if($data['sign_time']){
                $t=strtotime($data['sign_time']);
                $data['require_clear_time']=date('Y-m-d',$t+$protocol_set['require_clear_time']*24*60*60);
            }else{
                $data['require_clear_time']='';
            }
        }

        unset($data['supply_form']);
        unset($data['build_form']);
        unset($data['street_id']);
        unset($data['village_id']);
        unset($data['project_id']);
        unset($data['segment_id']);

        return showData($data);
    }
}

